package file

import (
	"io/ioutil"
	"regexp"
	"strings"
)

func Read(basePath string, fileName string, limit int) []string {
	fileName = basePath + "/" + fileName
	b, err := ioutil.ReadFile(fileName)
	if err != nil {
		panic(err)
	}

	// 过滤掉不发音的
	var bStr string = string(b)
	bStr = strings.Replace(bStr, "”", "", -1)
	bStr = strings.Replace(bStr, "“", "", -1)
	bStr = strings.Replace(bStr, "\r\n", "", -1)
	bStr = strings.Replace(bStr, " ", "", -1)

	var limitCount int = len([]rune(bStr))/limit + 1

	var runeB []rune = []rune(bStr)

	var res []string
	var i int
	var end int
	for i = 0; i < limitCount; i++ {
		end = (i + 1) * limit
		if (i+1)*limit > len(runeB) {
			end = len(runeB)
		}

		res = append(res, string(runeB[i*limit:end]))
	}

	return res
}

func GetDirFilesToAudio(path string) []string {
	files, err := ioutil.ReadDir(path)
	if err != nil {
		panic(err)
	}
	var textFiles []string
	var mp3Files map[string]int = map[string]int{}
	reg := regexp.MustCompile(`(.+)(_\d+.mp3)`)
	if reg == nil {
		panic("reg err")
	}

	for _, fi := range files {
		if fi.IsDir() {
			continue
		} else {
			fileName := fi.Name()
			regRes := reg.FindAllStringSubmatch(fileName, -1)
			if len(regRes) == 0 {
				textFiles = append(textFiles, fileName)
			} else {
				mp3Files[regRes[0][1]] = 1
			}
		}
	}

	if len(textFiles) == 0 {
		return []string{}
	}

	var res []string
	for _, item := range textFiles {
		// 去掉已经生成了的
		if mp3Files[item] == 1 {
			continue
		}
		res = append(res, item)
	}
	return res
}
